package br.com.cicero.futebol.controle;

import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.cicero.futebol.modelo.entidades.Time;
import br.com.cicero.futebol.modelo.repositorios.TimeRepository;

@ManagedBean
public class TimeBean {
	
	private Time time = new Time();
	private List<Time> times;
	
	public void adiciona() {
		
		EntityManager em = this.getManager();
		TimeRepository repository = new TimeRepository(em);
		
		if (this.time.getId() == null) {
			
			repository.adiciona(this.time);
			
		} else {
			
			repository.atualiza(this.time);
			
		}
		
		this.time = new Time();
		this.times = null;
				
	}
	
	public void preparaAlteracao() {
		
		Map<String, String> params = FacesContext.getCurrentInstance().
				getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager em = this.getManager();
		TimeRepository repository = new TimeRepository(em);
		this.time = repository.procura(id);
			
	}
	
	public void remove() {
		
		Map<String, String> params = FacesContext.getCurrentInstance().
				getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager em = this.getManager();
		TimeRepository repository = new TimeRepository(em);
		repository.remove(id);
		this.times = null;
				
	}
	
	public List<Time> getTimes() {
		
		if (this.times == null) {
			
			EntityManager em = this.getManager();
			TimeRepository repository = new TimeRepository(em);
			this.times = repository.getLista();
			
		}
		
		return this.times;
		
	}

	private EntityManager getManager() {
		
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext ec = context.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		
		return (EntityManager) request.getAttribute("EntityManager");
		
	}

	public Time getTime() {
		return time;
	}

	public void setTime(Time time) {
		this.time = time;
	}

	public void setTimes(List<Time> times) {
		this.times = times;
	}
	
}
